package ws.utils.collections.table;

import java.util.LinkedList;
import java.util.List;

/**
 * This class represents one table.
 * 
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class Table implements ITable {

  /** Row that represents the header row of this table. */
  protected Row header = new Row();
  /** Table rows. */
  protected List<Row> rowList = new LinkedList<Row>();

  public void addRow(Row row) {
    rowList.add(row);
  }

  public void addColumn(int nRow, Column col) {
    if (nRow < rowList.size()) {
      rowList.get(nRow).addColumn(col);
    } else {
      Row row = new Row();
      row.addColumn(col);
      rowList.add(row);
    }
  }

  public Row getHeader() {
    return header;
  }

  public void setHeader(Row header) {
    this.header = header;
  }

  public List<Row> getRowList() {
    return rowList;
  }

  public void setRowList(List<Row> rowList) {
    this.rowList = rowList;
  }

  @Override
  public String toString() {
    /* Write header. */
    String str = "#";
    for (Column col : header.getColumnList()) {
      str += col.content + "\t";
    }
    str += '\n';
    /* Write rows. */
    for (Row row : rowList) {
      str += row.toString();
    }
    return str;
  }

  public Object[][] toArray() {
    Object[][] ret = new Object[getRowCount()][getColumnCount()];

    for (int i = 0; i < getRowCount(); ++i) {
      ret[i] = rowList.get(i).getColumnList().toArray();
    }

    return ret;
  }

  public int getColumnCount() {
    if (rowList.isEmpty()) {
      return 0;
    }
    return rowList.get(0).getColumnList().size();
  }

  public int getRowCount() {
    return rowList.size();
  }

  public Object[] getColumnNames() {
    Object[] ret = new Object[getColumnCount()];

    for (int i = 0; i < getColumnCount(); ++i) {
      ret[i] = header.getColumn(i).content;
    }
    return ret;
  }

  public void addColumn(Column col) {
    assert col != null;
    for(Row row : rowList) {
      row.addColumn(new Column(col.name, col.content));
    }
  }

  public String getColumnContent(int rowIndex, int columnIndex) {
    if(rowIndex >= getRowCount() || columnIndex >= getColumnCount()) {
      throw new IllegalArgumentException("rowIndex should be less than '" + getRowCount()
              + "' and columnIndex should be less than '" + getColumnCount());
    }
    return rowList.get(rowIndex).getColumn(columnIndex).content;
  }
}
